import { Byte } from '../../api/io/Byte';
import { WelfareSignIn } from './WelfareSignIn';
import { ITimer } from '../../api/timer/ITimer';
import { IAsync } from '../../api/event/IAsync';



/**福利属性枚举*/
export const enum E_Welfare {
	/**签到*/
	SIGN_IN = 0,
	/**枚举数量*/
	EnumCount = 1
}


/**福利*/
export class Welfare {
	/**事件ID*/
	public static readonly EVENT_ID = 'STRUCT_DATA_WELFARE_EVENT_ID';
	/**整体更新事件ID（部分只需要监听整体变化）*/
	public static readonly TOTAL_EVENT_ID = 'STRUCT_DATA_WELFARE_TOTAL_EVENT_ID';
	/**缓存池*/
	private static POOL: Welfare[] = [];

	/**创建入口*/
	public static create(json?: string): Welfare {
		const c = this.POOL.pop() || new Welfare();
		c._destroyed = false;
		c.resetProperty();
		if (json) {
			c.parse(json);
		}
		return c;
	}


	/**已释放*/
	protected _destroyed = false;
	/**签到*/
	protected _signIn: WelfareSignIn = null;


	/**构建函数-私有，防止外部创建*/
	private constructor() {
	}


	/**释放*/
	public destroy(): void {
		if (this._destroyed) {
			return;
		}
		this._destroyed = true;
		this.resetProperty(true);
		if (Welfare.POOL.indexOf(this) === -1) {
			Welfare.POOL.push(this);
		}
	}

	/**签到*/
	public get signIn() {
		return this._signIn;
	}



	/**通过枚举获取值*/
	public getV(k: E_Welfare): any {
		switch (k) {
			case E_Welfare.SIGN_IN: return this._signIn;
			default: return null;
		}
	}


	/**通过枚举设置值*/
	public setV(k: E_Welfare, v: any): void {
		switch (k) {
			case E_Welfare.SIGN_IN: this._signIn = v; break;
			default: break;
		}
	}


	/**初始化*/
	public resetProperty(fromDestroy = false): void {
		//签到
		if (this._signIn) {
			this._signIn.destroy();
			this._signIn = null;
		}
		if (!fromDestroy) {
			this._signIn = WelfareSignIn.create();
		}
	}


	/**序列化*/
	public stringify(toString: boolean): string | any {
		const json: any = {};
		if (this._signIn) {
			json.signIn = this._signIn.stringify(false);
		}

		return toString ? JSON.stringify(json) : json;
	}


	/**反序列化*/
	public parse(jsonv: string | any): this {
		this.resetProperty();
		if (!jsonv) {
			return this;
		}
		const json = typeof (jsonv) === 'string' ? JSON.parse(jsonv) : jsonv;
		if (json.signIn) {
			this._signIn.destroy();
			this._signIn = WelfareSignIn.create(json.signIn);
		}
		return this;
	}


	/**序列化-二进制*/
	public toBytes(byte: Byte): void {
		if (!byte) {
			return;
		}
		this._signIn.toBytes(byte);
	}


	/**反序列化-二进制*/
	public fromBytes(byte: Byte): this {
		this.resetProperty();
		if (!byte) {
			return;
		}
		this._signIn.fromBytes(byte);
		return this;
	}


	/**克隆*/
	public clone(): Welfare {
		const byte = Byte.createFromPool();
		this.toBytes(byte);
		byte.pos = 0;
		const clonev = Welfare.create().fromBytes(byte);
		Byte.recoverToPool(byte);
		return clonev;
	}


	/**处理更新*/
	public processUpdate(jsonv: string): void {
		if (!jsonv) {
			return;
		}

		const eventID = Welfare.EVENT_ID;
		const us = JSON.parse(jsonv);

		for (let i = 0, len = us.length; i < len;) {
			const idx = us[i];
			//签到
			if (idx === E_Welfare.SIGN_IN) {
				const fui: string = us[i + 1];
				if (this._signIn) {
					this._signIn.processUpdate(fui);
				}
				else {
					console.error('Welfare signIn is null when update.');
				}
				IAsync.dispatch(eventID, idx);
				i += 2;
				continue;
			}

			console.error('[Struct Data] can not find enum in Welfare with idx = ' + idx + ', version maybe wrong.')
		}

		//全更事件
		ITimer.callLater(this, this.dispatchTotalUpdate);
	}


	/**比对不一致结果*/
	public getCompareInfo(other: Welfare): string {
		if (!other) {
			return null;
		}

		const updates: any[] = [];

		//签到
		{
			const ui = this._signIn.getCompareInfo(other._signIn);
			if (ui && ui.length > 0) {
				updates.push(E_Welfare.SIGN_IN, ui);
			}
		}

		const jsonv = updates.length === 0 ? null : JSON.stringify(updates);
		return jsonv;
	}


	/**全部更新*/
	protected dispatchTotalUpdate(): void {
		IAsync.dispatch(Welfare.TOTAL_EVENT_ID, this.getV(0));
	}

}
